package com.pl.code.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pl.code.entity.dto.template.AddTemplateDTO;
import com.pl.code.entity.dto.template.UpdateTemplateDTO;
import com.pl.code.entity.po.PlTemplate;
import com.pl.code.entity.vo.TemplateDetailsVO;
import com.pl.code.service.PlTemplateService;
import com.pl.core.annotation.PlRestController;
import com.pl.core.utils.AssertUtil;
import com.pl.data.core.entity.PageDTO;
import com.pl.data.core.response.Result;
import com.pl.data.core.utils.PoJoConverter;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;

/**
 * @ClasssName TemplateController
 * @Description 模板相关API
 * @Author Liuyh
 * @Date 2021/5/15
 * @Version V0.0.1
 */
@PlRestController("template")
@Validated
public class TemplateController {
    @Resource
    private PlTemplateService plTemplateService;
    /**
     * 通过id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Long id){
       PlTemplate plTemplate = plTemplateService.getById(id);
        AssertUtil.notNull(plTemplate,"未查询到模板数据");
        return Result.ok(TemplateDetailsVO.po2vo(plTemplate));
    }


    /**
     * 新增
     *
     * @param addTemplateDTO
     * @return
     */
    @PutMapping("save")
    public Result save(@Validated @RequestBody AddTemplateDTO addTemplateDTO){
        return Result.ok(plTemplateService.save(addTemplateDTO.dto2po()));
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    public Result delete(@Validated @NotNull(message = "id不能为空") @PathVariable("id") Long id) {
        return Result.ok(plTemplateService.removeById(id));
    }

    /**
     * 修改
     *
     * @param updateTemplateDTO
     * @return
     */
    @PostMapping("update")
    public Result update(@Validated @RequestBody UpdateTemplateDTO updateTemplateDTO){
        return Result.ok(plTemplateService.updateById(updateTemplateDTO.dto2po()));
    }

    /**
     * 分页查询
     *
     * @param page
     * @param keywords
     * @return
     */
    @GetMapping("/page")
    public Result page(PageDTO page, String keywords) {
        LambdaQueryWrapper<PlTemplate> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(keywords)) {
            queryWrapper.like(PlTemplate::getName, keywords);
        }
        IPage pageData = plTemplateService.page(page.toPage(), queryWrapper);
        return Result.ok(PoJoConverter.po2vo(pageData));
    }


}
